package nl.jjsoft.airlock.view.presenters
{
	import flash.desktop.Clipboard;
	import flash.system.Capabilities;
	
	import nl.jjsoft.airlock.domain.Session;
	import nl.jjsoft.airlock.event.ApplicationEvent;
	import nl.jjsoft.airlock.utils.Constants;
	import nl.jjsoft.airlock.utils.DbUtils;
	import nl.jjsoft.airlock.utils.ResourceFactory;
	
	import org.swizframework.storage.ISharedObjectBean;
	
	public class ApplicationPresenter extends AbstractPresenter
	{
		[Inject]
		public var session:Session;
		
		[Inject]
		public var dbUtils:DbUtils;
		
		[Inject]
		public var so:ISharedObjectBean;
		
		[Inject]
		public var resourceFactory:ResourceFactory;
		
		public function ApplicationPresenter()
		{
			super();
		}
		
		[Mediate(event="ApplicationEvent.INITIALIZE")]
		public function initApplication():void {
			session.dbFilePath = dbUtils.getLastSelectedDB();
			retrieveLanguageOrFallBackToOsIfNoneExists();
			dispatcher.dispatchEvent(new ApplicationEvent(ApplicationEvent.DISPLAY_LOGIN_VIEW, true));
		}
		
		[Mediate(event="ApplicationEvent.DESTROY")]
		public function destroy(event:ApplicationEvent):void {
			Clipboard.generalClipboard.clear();
		}
		
		private function retrieveLanguageOrFallBackToOsIfNoneExists():void {
			var locale:String = Capabilities.languages[0].replace("-", "_");
			if (contains(resourceFactory.supportedLocales, locale)) {
				locale = so.getString(Constants.LOCALE, locale);
			} else {
				locale = resourceFactory.defaultLocale;
			}
			
			resourceFactory.changeLocale(locale);
			session.currentLocale = locale;
		}
		
		private function contains(locales:Array, locale:String):Boolean {
			for (var i:int = 0; i < locales.length; i++) {
				if (locale == locales[i]) {
					return true;
				}	
			}
			
			return false;
		}
	}
}